package web.bean;

import core.entity.Post;
import core.service.PostService;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import java.util.HashSet;
import java.util.List;

/**
 * Created by Christian Waickem on 9/29/2014.
 */
@ManagedBean
@SessionScoped
public class PostBean {

    String searchString;

    Long id;

    Post post;

    boolean dots = false;

    public List<Post> postsList;

    @ManagedProperty(value = "#{postService}")
    PostService postService;

    public PostService getPostService() {
        return postService;
    }

    public void setPostService(PostService postService) {
        this.postService = postService;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Post getPost() {
        return post;
    }

    public void setPost(Post post) {
        this.post = post;
    }

    public String getSearchString() {
        return searchString;
    }

    public void setSearchString(String searchString) {
        this.searchString = searchString;
    }


    public void initPostsData(String searchString) {
        if (searchString != "") {
            List<Post> contentList = postService.searchPostByContent(searchString);
            List<Post> titleList = postService.searchPostByString(searchString);

            if(contentList.size() == 0 && titleList.size() == 0){
                postsList.clear();
                return;
            }

            HashSet hs = new HashSet();
            postsList.clear();

            for(Post post : titleList){
                if(!hs.contains(post.getId())){
                    hs.add(post.getId());
                    postsList.add(post);
                }
            }

            for(Post post : contentList){
                if(!hs.contains(post.getId())){
                    hs.add(post.getId());
                    postsList.add(post);
                }
            }

            /*if(contentList.size() != 0){
                hs.addAll(contentList);
            }

            if(titleList.size() != 0){
                hs.addAll(titleList);
            }

            if(hs.size() != 0) {
                postsList.clear();
                postsList.addAll(hs);
            } else{
                postsList.clear();
            }*/
        } else{
            postsList = postService.getAllShortContent();
        }
    }

    public List<Post> getPostsList() {
        return postsList;
    }

    public void initPost() {
        if (this.id != null) {
            post = postService.findPostById(id);
        } else {
            post = new Post();
        }
    }

}
